try{
	define(function(){
		var nano=function(template,data) {
			if(typeof (template)=='string'){
				return template.replace(/\$\{([\w\.]*)\}/g,function(str,key) {
					var keys=key.split("."),v=data[keys.shift()];
					for(var i=0,l=keys.length;i<l;i++)
						v=v[keys[i]];
					return(typeof v!=="undefined"&& v!==null)? v:"";
				});
			} else {
				return null;
			}
		};

		var getUrlKey=function(){
			if($E.dataService.key){
				if($E.pluginServices['plugin.email.'+$E.dataService.key]){
					return 'plugin.email.'+$E.dataService.key;
				}else{
					return 'plugin.email';
				}
			}else{
				return 'plugin.email';
			}
		}


		var mergeAjax1=function(ajaxUrl,dataString,type){
			var resultCode=0;
			var fileUrl;
			var errorMsg;
			var result;
			$F.pluginService(getUrlKey(),ajaxUrl,{
				data:dataString,
				async: false,
				success: function(data) {
					if (data.code > 0) {
						resultCode=1;
						if(type=='common'||type=='print'){
							fileUrl=data.value.urlPath;
						}
					} else{
						errorMsg=data.message;
					}
				},
				fail : function(jqXHR, textStatus, errorThrown){
					errorMsg=jqXHR.responseText;
				},
				always: function() {
					if(type=='common'||type=='print'){
						result={'code':resultCode,'value':fileUrl,'message':errorMsg};
					}else{
						result={'code':resultCode,'value':resultCode,'message':errorMsg};
					}
					console.log(result);
				}
			});
			return result;
		};

		var mergeAjax = function (method, data, type) {
			var resultCode = 0;
			var fileUrl;
			var errorMsg;
			var result;
			var resultValue;
			var pluginService = $E.pluginServices[getUrlKey()];
			if (!pluginService) {
				throw new Error('插件未定义：' + pluginId);
			}
			var threadId = Date.now(),
				start = new Date();
			if (pluginService.toLowerCase().startWith('http')) {
				// 通过proxy代理
				url = pluginService + '/' + method;
			} else {
				// 直接访问同一个JVM下的其他WebApp服务
				url = method ? (pluginService + '/' + method) : serviceUrl;
			}
			if (H5Utils.isChrome) {
				console.info(url, 'color:#0d6b2b');
			} else {
				console.info(url);
			}
			Ajax.post({
				url : url,
				data : data,
				contentType : 'application/json;charset=UTF-8',
				async : false,
				cache : false,
				headers : {
	//				'THREADID' : threadId,
	//				'TERMINAL' : ($E.admin ? 'admin' : '')
				},
				success : function(data) {
					var t = (new Date() - start);
					if (t > 500) {
						if (H5Utils.isChrome)
							console.warn('%c[PluginService - ' + threadId + '] ' + method + ', took ' + t + '\'ms', "color:#ff0000;font-size: 1.5em");
						else
							console.warn('[PluginService - ' + threadId + '] ' + method + ', took ' + t + '\'ms');
					}
					//	console.error(data);
					if (data.code > 0) {
						resultCode=1;
						resultValue=data.value;
						if(type=='common'||type=='print'){
							fileUrl=data.value.urlPath;
						}
					} else{
						errorMsg=data.message;
					}
				},
				fail : function(jqXHR, textStatus, errorThrown) {
					errorMsg=jqXHR.responseText;
				},
				always : function() {
					if(type=='common'||type=='print'){
						result={'code':resultCode,'value':fileUrl,'message':errorMsg};
					}else{
						result={'code':resultCode,'value':resultValue,'message':errorMsg};
					}
					console.log(result);
				}
			})
			return result;
		};


		var getCustomerGuid=function(contentJson){
			var customer_guid=contentJson.cust.customer_guid;
			if (typeof(customer_guid) == "undefined") {
				customer_guid='';
			}
			return $.trim(customer_guid);
		};
		var getEpid=function(){
			var epid = $E.staff.epidSql;
			if(!epid){
				epid="";
			}
			return epid.toLowerCase();
		};
		window.mergeUtil = {

			getPluginServicesKey:function(){
				return getUrlKey();
			},

			pluginServiceNew:function(pluginId, method, options){
				var pluginService = $E.pluginServices[pluginId];
				if(!pluginService){
					throw new Error('插件未定义：' + pluginId);
				}
				var threadId = Date.now(),
					data = JSON.stringify(options.data),
					url,
					start = new Date(),
					busyId = options.silent ? false : $F.busyShow(options.title || '');
				if (pluginService.toLowerCase().startWith('http')) {
					// 通过proxy代理
					url = pluginService + '/' + method;
				} else {
					// 直接访问同一个JVM下的其他WebApp服务
					url = method ? (pluginService + '/' + method) : serviceUrl;
				}
				if (H5Utils.isChrome){
					console.info('%c[' + pluginId + ' - ' + threadId + '] ' + url, 'color:#0d6b2b');
				}else{
					console.info('[' + pluginId + ' - ' + threadId + '] ' + url);
				}
				Ajax.post({
					url : url,
				data : data,
				contentType : 'application/json;charset=UTF-8',
				async : options.async,
				cache : false,
				dataType:  options.dataType || 'json',
				headers : {
//					'THREADID' : threadId,
//					'TERMINAL' : ($E.admin ? 'admin' : '')
				},
				success : function(data) {
					var t = (new Date() - start);
					if (t > 500) {
						if (H5Utils.isChrome)
							console.warn('%c[PluginService - ' + threadId + '] ' + method + ', took ' + t + '\'ms', "color:#ff0000;font-size: 1.5em");
						else
							console.warn('[PluginService - ' + threadId + '] ' + method + ', took ' + t + '\'ms');
					}
					//	console.error(data);
					try {
						if ($.isFunction(options.success))
							options.success(data);
					} catch (e) {
						console.error(e);
					}
				},
				fail : function(jqXHR, textStatus, errorThrown) {
					if (jqXHR.status == 200)
						$F.err('$F - pluginService', textStatus);
					else
						$F.err('$F - pluginService', '[STATUS:' + jqXHR.status + ']', textStatus);
					if ($.isFunction(options.fail)) {
						options.fail(jqXHR, textStatus, errorThrown);
					}
				},
				always : function() {
					if (!options.silent)
						$F.busyHide(busyId);
					if ($.isFunction(options.always)) {
						options.always();
					}
				}
				})
			},
		    /**
             * 根据传入的json以及模板URL，进行模板合并，作为邮件正文，然后根据传入的主题，收件人，抄送人，进行发送
             * @method templetMail
             * @param contentJson{json} 合并模板的内容
             * @param filePath{String} 模板文件路径
             * @param subject {String}邮件主题
             * @param recipient{String} 邮件收件人，多个收件人用;(分号)分隔
             * @param recipient_cc {String}邮件抄送人，多个抄送人用;(分号)分隔
             * @param sendDate{String} 发送时间，直接给我字符串
             * @param mailAttach{Array} 发送邮件的附件路径，有多个附件时候，用Array对象传递
             * @param extendParam {String}当前动态页面发邮件的扩展字段
             * @param contentType {Integer}0:通过模板合并获得正文，1:直接用传递的字符串作为正文
             * @return result {json}返回的json对象
             */
			templetMail:function(contentJson,filePath,subject,recipient,recipient_cc,sendDate,mailAttach,extendParam,contentType,mailfrom,contentType1,recipient_bcc,customerFlag){
				var mailAttach_temp='';
				extendParam=nano(extendParam,{'dynamicPage':contentJson});
				if(parseInt(contentType)==1){
					filePath=nano(filePath,{'dynamicPage':contentJson});
				}
				if(mailAttach!=null){
					for(var i=0;i<mailAttach.length;i++){
						if(i!=mailAttach.length-1){
							mailAttach_temp=mailAttach_temp+"mailAttach="+mailAttach[i]+"&";
						}else{
							mailAttach_temp=mailAttach_temp+"mailAttach="+mailAttach[i];
						}
					}
				}
				var customer_guid="";
				if(typeof(customerFlag)!="undefined"&&customerFlag){
					customer_guid=getCustomerGuid(contentJson);
				}
				if (!mailfrom) {
					mailfrom = '';
				}
				if(typeof(recipient_bcc)=="undefined"){
					recipient_bcc="";
				}
				var dataString='from='+mailfrom+'&epid='+encodeURIComponent(getEpid())+'&contentJson='+encodeURIComponent(JSON.stringify(contentJson))+'&filePath='+encodeURIComponent(filePath)+'&subject='+encodeURIComponent(subject)+'&recipient='+encodeURIComponent(recipient)+'&recipient_cc='+encodeURIComponent(recipient_cc)+'&sendDate='+encodeURIComponent(sendDate)+'&staff_id='+encodeURIComponent($E.staff.id)+'&group_id='+encodeURIComponent($E.staff.current.groupId)+'&'+encodeURI(mailAttach_temp)+'&type=mail&extendParam='+encodeURIComponent(extendParam)+'&Customer_guid='+encodeURIComponent(customer_guid)+'&contentType='+encodeURIComponent(contentType)+'&contentType1='+encodeURIComponent(contentType1)+'&recipient_bcc='+encodeURIComponent(recipient_bcc);
				var result=mergeAjax( 'SaveTempletFileService',dataString,'mail');
				return result;
			},

		    /**
             * 根据传入的json以及模板URL，进行模板合并，并且返回合并后文件(带有打印按钮的html文件)的临时http访问路径
             * @method templetPrint
             * @param contentJson {json} 合并模板的内容
             * @param filePath {String}模板文件路径
             * @return result {json}返回的json对象
             */
			templetPrint:function(contentJson,filePath){
				var result;
				var fileExtension = filePath.substring(filePath.lastIndexOf('.') + 1);
//				if(fileExtension=='xml'){
//					var dataString='epid='+encodeURIComponent(getEpid())+'&contentJson='+encodeURIComponent(JSON.stringify(contentJson))+'&filePath='+encodeURIComponent(filePath)+'&type=common';
//					result=mergeAjax( '/SaveTempletFileService',dataString,'common');
//				}else{
//					var dataString='epid='+encodeURIComponent(getEpid())+'&contentJson='+encodeURIComponent(JSON.stringify(contentJson))+'&filePath='+encodeURIComponent(filePath)+'&type=print';
//					result=mergeAjax( '/SaveTempletFileService',dataString,'print');
//				}
				var dataString='epid='+encodeURIComponent(getEpid())+'&contentJson='+encodeURIComponent(JSON.stringify(contentJson))+'&filePath='+encodeURIComponent(filePath)+'&type=print';
				result=mergeAjax( 'SaveTempletFileService',dataString,'print');
				return result;

			},

		    /**
             * 根据传入的json以及模板URL，进行模板合并，并且返回合并后文件的临时http访问路径
             * @method templetMerge
             * @param contentJson {json}合并模板的内容
             * @param filePath {String}模板文件路径
             * @return result{json} 返回的json对象
             */
			templetMerge:function(contentJson,filePath,printtype,pdfFlag,newFilename,ngsUploadFlag){
				if(typeof(newFilename)=="undefined"){
					newFilename="";
				}
				var dataString='ngsUploadFlag='+ngsUploadFlag+'&newFilename='+encodeURIComponent(newFilename)+'&pdfFlag='+pdfFlag+'&printtype='+printtype+'&epid='+encodeURIComponent(getEpid())+'&contentJson='+encodeURIComponent(JSON.stringify(contentJson))+'&filePath='+encodeURIComponent(filePath)+'&type=common';
				var result=mergeAjax( 'SaveTempletFileService',dataString,'common');
				return result;
			},

			/**
             * 根据传入的json以及短信正文，进行模板合并，然后插入documentout表作为发送短信记录
             * @method templetSmsMerge
             * @param sms_content {String}正文内容
             * @param sms_phone {String}短信号码
             * @param sms_sendDate{String} 期望发送时间
             * @param extendParam{json} 当前动态页面发短信的扩展字段
             * @return result {json}返回的json对象
             */
			templetSmsMerge:function(sms_content,sms_phone,sms_sendDate,extendParam){
				var ajaxUrl = 'SaveSmsService';
				var data = {
					staff_id: $E.staff.id,
					group_id: $E.staff.current.groupId,
					epid: getEpid(),
					form: {
						sms_content: sms_content,
						sms_phone: sms_phone,
						sms_sendDate: sms_sendDate,
						sms_jsonData: extendParam
					},
				};
				return mergeAjax(ajaxUrl, JSON.stringify(data), 'sms');
			},
			/**
             * 根据传入的json以及传真文件路径，进行模板合并，然后插入documentout表作为发送传真记录
             * @method templetFaxMerge
             * @param contentJson {json}合并模板的内容
             * @param fax_saveWebAttach {Array} 传真模板路径，有多个传真文件用Array对象传递
             * @param fax_phone{String} 传真号码
             * @param fax_sendDate{String} 期望发送时间
             * @param extendParam {String}当前动态页面发传真的扩展字段
             * @return result{json} 返回的json对象
             */
			templetFaxMerge:function(contentJson,fax_saveWebAttach,fax_phone,fax_sendDate,extendParam){
				var fax_saveWebAttach_temp='';
				extendParam=nano(extendParam,{'dynamicPage':contentJson});
				if(fax_saveWebAttach!=null){
					for(var i=0;i<fax_saveWebAttach.length;i++){
						if(i!=fax_saveWebAttach.length-1){
							fax_saveWebAttach_temp=fax_saveWebAttach_temp+"fax_Webattach="+fax_saveWebAttach[i]+"&";
						}else{
							fax_saveWebAttach_temp=fax_saveWebAttach_temp+"fax_Webattach="+fax_saveWebAttach[i];
						}
					}
				}
                var customer_guid=getCustomerGuid(contentJson);
				var ajaxurl='SaveFaxService?staff_id='+encodeURIComponent($E.staff.id)+'&group_id='+encodeURIComponent($E.staff.current.groupId)+'&customer_guid='+encodeURIComponent(customer_guid)+'&epid='+encodeURIComponent(getEpid());
				var dataString='fax_customer_json='+encodeURIComponent(JSON.stringify(contentJson))+'&'+fax_saveWebAttach_temp+'&fax_phone='+encodeURIComponent(fax_phone)+'&fax_sendDate='+encodeURIComponent(fax_sendDate)+'&fax_jsonData='+encodeURIComponent(extendParam);
				var result=mergeAjax( ajaxurl,dataString,'fax');
				return result;
			}
		};
		return mergeUtil;
	});
}catch(e){
	console.log(e);
}
